<template>
  <div class="goods-sku">
    <dl v-for="item in goods.specs" :key="item.id">
        <dt>{{item.name}}</dt>
        <dd>
            <template v-for="val in item.values" :key="val.name">
                <img :class="{selected:val.selected,disabled:val.disabled}" @click="changeSku(item,val)" v-if="val.picture" :src="val.picture" :title="val.name">
                <span :class="{selected:val.selected,disabled:val.disabled}" @click="changeSku(item,val)" v-else>{{val.name}}</span>
            </template>
        </dd>
    </dl>
  </div>
</template>
<script>
import powerSet from '@/vender/power-set'
const spliter = '★'
// 得到一个路径字典对象
const getPathMap = (skus) => {
  // 1. 得到所有的sku集合  props.goods.skus
  // 2. 从所有的sku中筛选出有效的sku
  // 3. 根据有效的sku使用power-set算法得到子集
  // 4. 根据子集往路径字典对象中存储 key-value
  const pathMap = {}
  skus.forEach(sku => {
    if (sku.inventory > 0) {
      // 计算当前有库存的sku的子集
      // 例如：[1,2,3] ==> [[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
      // 可选值数组
      const valueArr = sku.specs.map(val => val.valueName)
      // 可选值数组 子集
      const valueArrPowerSet = powerSet(valueArr)
      // 遍历子集，往pathMap插入数据
      valueArrPowerSet.forEach(arr => {
        // 根据arr得到字符串的key，约定key是：['蓝色','美国'] ===> '蓝色★美国'
        const key = arr.join(spliter)
        // 给pathMap设置数据
        if (pathMap[key]) {
          pathMap[key].push(sku.id)
        } else {
          pathMap[key] = [sku.id]
        }
      })
    }
  })
  return pathMap
}

// 得到当前选中规格集合
const getSelectedArr = (specs) => {
    const selectedArr = []
    specs.forEach(spec => {
        const selectedVal = spec.values.find(val => val.selected)
        selectedArr.push(selectedVal ? selectedVal.name : undefined)

    })
    return selectedArr
}

// 更新按钮禁用状态
const updateDisabledStatus = (specs, pathMap) => {
    specs.forEach((spec,i) => {
        const selectedArr = getSelectedArr(specs)
        spec.values.forEach(val => {
            // 已经选中的按钮不用判断
            if(val.name === selectedArr[i]) return false
            // 未选中的替换对应的值
            selectedArr[i] = val.name
            // 过滤无效值得到Key
            const key = selectedArr.filter(v=> v).join(spliter)
            // 设置禁用状态
            val.disabled = !pathMap[key]
        })
    })
}
      // 初始化选中状态
      const initSelectedStatus = (goods, skuId) => {
          const sku = goods.skus.find(sku => sku.id === skuId)
          if(sku) {
              goods.specs.forEach((spec,i)=> {
                  const value = sku.specs[i].valueName
                  spec.values.forEach(val => {
                      val.selected = val.name === value
                  })
              })
          }
      }

export default {
  name: 'GoodsSku',
  props: {
      goods: {
          type: Object,
          default: () => ({specs: [], skus: [] })
      },
      skuId: {
          type: String,
          default: ''
      }
  },
  setup(props,{emit}) {
      const pathMap = getPathMap(props.goods.skus)
       // 根据传入的skuId默认选中规格按钮
       // 根据skuId初始化选中
       if (props.skuId) {
       initSelectedStatus(props.goods, props.skuId)
       }
      //  initSelectedStatus(props.goods, props.skuId)

       // 组件初始化的时候更新禁用状态
       updateDisabledStatus(props.goods.specs, pathMap)
    //   console.log(pathMap, 'pathMap')
      const changeSku = (item, val) => {
           // 如果是禁用状态不作为
           if(val.disabled) return false
          // 1. 选中与取消选中逻辑
          if (val.selected) {
              val.selected = false
          } else {
              item.values.forEach(bv => {bv.selected = false })
              val.selected = true
          }
           // 点击的时候更新禁用状态
           updateDisabledStatus(props.goods.specs, pathMap)
           // 触发change事件将sku数据传递出去
           const selectedArr = getSelectedArr(props.goods.specs).filter(v => v)
           if (selectedArr.length === props.goods.specs.length) {
               const skuIds = pathMap[selectedArr.join(spliter)]
               const sku = props.goods.skus.find(sku => sku.id === skuIds[0])
               // 传递
               emit('change',{
                   skuId: sku.id,
                   price: sku.price,
                   oldPrice: sku.oldPrice,
                   inventory: sku.inventory,
                   specsText: sku.specs.reduce((p, n) => `${p} ${n.name}：${n.valueName}`, '').replace(' ', '')
               })
           } else {
               emit('change', {})
           }
      }


      return {changeSku}
  },
  
}
</script>
<style scoped lang="less">
.sku-state-mixin () {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;
  &.selected {
    border-color: @xtxColor;
  }
  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}
.goods-sku {
  padding-left: 10px;
  padding-top: 20px;
  dl {
    display: flex;
    padding-bottom: 10px;
    align-items: center;
    dt {
      width: 50px;
      color: #999;
    }
    dd {
      flex: 1;
      color: #666;
      line-height: 40px;
      > img {
        width: 50px;
        height: 50px;
        .sku-state-mixin ();
      }
      > span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        .sku-state-mixin ();
      }
    }
  }
}
</style>